import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/// 假设这些环境变量已经在你的环境配置中设置
const API_PROXY_TARGET = process.env.API_PROXY_TARGET || 'http://127.0.0.1:5555';
const SERVER_HOST = process.env.SERVER_HOST || '127.0.0.1';
const SERVER_PORT = process.env.SERVER_PORT || 3535;

export default defineConfig({
  plugins: [
    vue(),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  server: {
    proxy: {
      '/api': {
        target: API_PROXY_TARGET,
        changeOrigin: true,
        rewrite: (path) => {
          try {
            return path.replace(/^\/api/, '');
          } catch (error) {
            console.error('Error rewriting path:', error);
            return path; // 如果替换出错，保持原路径
          }
        }
      }
    },
    host: SERVER_HOST,
    port: SERVER_PORT
  },
  build: {

    chunkSizeWarningLimit: 5000,
    rollupOptions: {
      output: {
        manualChunks(id) {
          try {
            // 更健壮的路径处理逻辑
            const pathParts = id.toString().split('node_modules/');
            if (pathParts.length > 1) {
              return pathParts[1].split('/')[0].toString();
            }
          } catch (error) {
            console.error('Error handling manual chunks:', error);
          }
          // 如果处理失败，让Rollup按默认方式处理
          return undefined;
        },
        chunkFileNames: (chunkInfo) => {
          // 保持原有的文件命名逻辑不变
          const facadeModuleId = chunkInfo.facadeModuleId
            ? chunkInfo.facadeModuleId.split('/')
            : [];
          const fileName =
            facadeModuleId[facadeModuleId.length - 2] || '[name]';
          return `js/${fileName}/[name].[hash].js`;
        }
      }
    }
  }
})